package com.ruicar.afs.cloud.apply.pre.loan.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.ruicar.afs.cloud.apply.business.service.ApplySequenceService;
import com.ruicar.afs.cloud.apply.common.entity.*;
import com.ruicar.afs.cloud.apply.pre.loan.condition.*;
import com.ruicar.afs.cloud.apply.pre.loan.service.*;
import com.ruicar.afs.cloud.apply.pre.loan.vo.AffiliatedUnitVO;
import com.ruicar.afs.cloud.apply.pre.loan.vo.AllOrderInfoVO;
import com.ruicar.afs.cloud.apply.pre.loan.vo.DicDataVO;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.parameter.commom.enums.*;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * @description: 申请提报
 * @author: sijun.yu
 * @date: 2020/5/12 13:18
 */
@Slf4j
@RestController
@RequestMapping("/order")
@AllArgsConstructor
public class ApplyReportController {

    private ApplyReportService reportService;
    private ApplyOrderInfoService orderInfoService;
    private ApplyAffiliatedUnitService affiliatedUnitService;
    private ApplyCarDetailsService carDetailsService;
    private ApplyChannelInfoService channelInfoService;
    private ApplyProductService productService;
    private ApplySequenceService sequenceService;
    private ApplyModifyHistoryService modifyHistoryService;

    /**
     * 获取业务类型参数
     *
     * @param condition
     * @return
     */
    @PostMapping(value = "/getBusinessParam")
    @ApiOperation("获取业务类型参数")
    public IResponse<List<DicDataVO>> getBusinessParaList(@ModelAttribute ApplyReportCondition condition) {

        List resultList = new ArrayList();
        if ("car_type".equals(condition.getFieldName())) {
            List<String> list = channelInfoService.queryCarType(condition);
            for (int i = 0; i < list.size(); i++) {
                DicDataVO vo = new DicDataVO();
                vo.setValue(list.get(i));
                vo.setTitle(CarType.getName(list.get(i)));
                resultList.add(vo);
            }
        } else {
            List<ApplyBusinessConfig> list = reportService.getBusinessOptionList(condition);
            for (int i = 0; i < list.size(); i++) {
                DicDataVO vo = new DicDataVO();
                if ("car_nature".equals(condition.getFieldName())) {
                    vo.setValue(list.get(i).getCarNature());
                    vo.setTitle(CarNature.getName(list.get(i).getCarNature()));
                } else if ("operate_way".equals(condition.getFieldName())) {
                    vo.setValue(list.get(i).getOperateWay());
                    vo.setTitle(OperateWay.getName(list.get(i).getOperateWay()));
                } else if ("affiliated_way".equals(condition.getFieldName())) {
                    vo.setValue(list.get(i).getAffiliatedWay());
                    vo.setTitle(AffiliatedWay.getName(list.get(i).getAffiliatedWay()));
                } else if ("car_purpose".equals(condition.getFieldName())) {
                    vo.setValue(list.get(i).getCarPurpose());
                    vo.setTitle(CarPurpose.getName(list.get(i).getCarPurpose()));
                }
                resultList.add(vo);
            }
        }
        return IResponse.success(resultList);
    }

    /**
     * 查询订单信息
     *
     * @param condition
     * @return
     */
    @PostMapping(value = "/getOrderInfo")
    @ApiOperation("查询订单信息")
    public IResponse<ApplyOrderInfo> getOrderInfo(@ModelAttribute ApplyReportCondition condition) {

        ApplyOrderInfo applyOrderInfo = orderInfoService.getOrderInfoByApplyNo(condition.getApplyNo());
        return IResponse.success(applyOrderInfo);
    }

    /**
     * 保存订单信息
     *
     * @param condition
     * @return
     */
    @PostMapping(value = "saveOrderInfo")
    @ApiOperation("保存订单信息")
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(value = "apply_order_info", allEntries = true)
    public IResponse saveOrderInfo(@RequestBody ApplyReportCondition condition) {

        String applyNo = sequenceService.getTempNoForApply();// 临时编号
        ApplyOrderInfo orderInfo = orderInfoService.saveOrderInfo(applyNo, condition);
        channelInfoService.saveChannelInfo(applyNo, condition);
        return IResponse.success(orderInfo);
    }

    /**
     * 更新订单信息
     *
     * @param condition
     * @return
     */
    @PostMapping(value = "updateOrderInfo")
    @ApiOperation("更新订单信息")
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(value = "apply_order_info", allEntries = true)
    public IResponse updateOrderInfo(@RequestBody ApplyReportCondition condition) {

        ApplyOrderInfo orderInfo = orderInfoService.getOrderInfoByApplyNo(condition.getApplyNo());
        if (orderInfo != null) {
            orderInfoService.updateOrderInfo(orderInfo, condition);
            ApplyChannelInfo channelInfo = channelInfoService.getChannelInfoByApplyNo(condition.getApplyNo());
            if (channelInfo != null) {
                channelInfoService.updateChannelInfo(channelInfo, condition);
            } else {
                channelInfoService.saveChannelInfo(condition.getApplyNo(), condition);
            }
        } else {
            return IResponse.fail("订单信息不存在");
        }
        return IResponse.success(Boolean.TRUE);
    }

    /**
     * 查询挂靠信息
     *
     * @param condition
     * @return
     */
    @PostMapping(value = "/getAffiliatedInfo")
    @ApiOperation("查询挂靠信息")
    public IResponse<AffiliatedUnitVO> getAffiliatedUnit(@ModelAttribute ApplyReportCondition condition) {

        AffiliatedUnitVO vo = new AffiliatedUnitVO();
        affiliatedUnitService.getAffiliatedUnit(condition.getApplyNo(), condition.getAffiliatedWay(), vo);
        return IResponse.success(vo);
    }

    /**
     * 保存挂靠信息
     *
     * @param condition
     * @return
     */
    @PostMapping(value = "saveAffiliatedUnit")
    @ApiOperation("保存挂靠信息")
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(value = "apply_affiliated_unit", allEntries = true)
    public IResponse saveAffiliatedUnit(@RequestBody AffiliatedUnitCondition condition) {

        // 判断是否存在
        String applyNo = condition.getApplyNo();
        ApplyAffiliatedUnit applyAffiliatedUnit = affiliatedUnitService.getAffiliatedUnitByApplyNo(applyNo);
        if (applyAffiliatedUnit != null) {
            return IResponse.fail("挂靠信息已存在");
        }
        // 保存挂靠信息
        ApplyAffiliatedUnit affiliatedUnit = affiliatedUnitService.saveOrUpdateAffiliatedUnit(applyNo, condition);

        return IResponse.success(affiliatedUnit);
    }

    /**
     * 更新挂靠单位
     *
     * @param condition
     * @return
     */
    @PostMapping(value = "updateAffiliatedUnit")
    @ApiOperation("更新挂靠单位")
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(value = "apply_affiliated_unit", allEntries = true)
    public IResponse updateAffiliatedUnit(@RequestBody AffiliatedUnitCondition condition) {

        ApplyAffiliatedUnit affiliatedUnit = affiliatedUnitService.getAffiliatedUnitByApplyNo(condition.getApplyNo());
        if (affiliatedUnit == null) {
            return IResponse.fail("挂靠信息不存在");
        } else {
            affiliatedUnitService.updateAffiliatedUnit(affiliatedUnit, condition);
        }

        return IResponse.success(Boolean.TRUE).setMsg("更新成功");
    }

    /**
     * 业务选择页面汇总保存
     *
     * @return
     */
    @ApiOperation("业务选择页面汇总保存")
    @Transactional(rollbackFor = Exception.class)
    @PostMapping("/saveBusinessOption")
    @CacheEvict
    public IResponse saveBusinessOption(@RequestBody AllOrderCondition condition) {

        AllOrderInfoVO vo = new AllOrderInfoVO();
        String applyNo = "";
        // 保存或更新订单信息
        ApplyOrderInfo orderInfo = orderInfoService.getOrderInfoById(condition.getOrderInfo().getId());
        if (orderInfo != null) {
            applyNo = orderInfo.getApplyNo();
            orderInfoService.updateOrderInfo(orderInfo, condition.getOrderInfo());
            ApplyChannelInfo channelInfo = channelInfoService.getChannelInfoByApplyNo(condition.getApplyNo());
            if (channelInfo != null) {
                channelInfoService.updateChannelInfo(channelInfo, condition.getOrderInfo());
            } else {
                channelInfoService.saveChannelInfo(condition.getApplyNo(), condition.getOrderInfo());
            }
        } else {
            applyNo = sequenceService.getTempNoForApply();// 申请编号
            orderInfo = orderInfoService.saveOrderInfo(applyNo, condition.getOrderInfo());
            channelInfoService.saveChannelInfo(applyNo, condition.getOrderInfo());
        }
        vo.setApplyNo(applyNo);
        vo.setOrderInfo(orderInfo);
        // 保存或更新挂靠信息
        if (AffiliatedWay.NO.getIndex().equals(condition.getOrderInfo().getAffiliatedWay())) {
            ApplyAffiliatedUnit affiliatedUnit = affiliatedUnitService.getAffiliatedUnitByApplyNo(applyNo);
            if (affiliatedUnit != null) {
                affiliatedUnitService.removeById(affiliatedUnit.getId());
            }
        } else {
            ApplyAffiliatedUnit affiliatedUnit = affiliatedUnitService.getAffiliatedUnitById(condition.getAffiliatedInfo().getId());
            if (affiliatedUnit != null) {
                affiliatedUnitService.updateAffiliatedUnit(affiliatedUnit, condition.getAffiliatedInfo());
            } else {
                affiliatedUnit = affiliatedUnitService.saveOrUpdateAffiliatedUnit(applyNo, condition.getAffiliatedInfo());
            }
            vo.setAffiliatedInfo(affiliatedUnit);
        }
        // 保存或更新车辆信息
        CarInfoCondition carInfoCondition = condition.getCarInfo();
        carInfoCondition.setCarNature(condition.getOrderInfo().getCarNature());
        ApplyCarDetails carDetails = carDetailsService.getCarDetailsById(carInfoCondition.getId());
        if (carDetails != null) {
            productService.updateFinanceInfoForSalePrice(applyNo, carDetails, carInfoCondition);
            carDetailsService.updateCarInfo(carDetails, carInfoCondition);
        } else {
            carDetails = reportService.saveOrUpdateCarInfo(applyNo, carInfoCondition);
        }
        vo.setCarInfo(carDetails);
        return IResponse.success(vo);
    }

    /**
     * 保存资产变更前的需要展示的数据-数据留痕
     *
     * @param condition
     * @return
     */
    @PostMapping("/saveAssertData")
    public IResponse saveAssertData(@RequestBody AllOrderCondition condition) {

        return this.reportService.saveAssertData(condition);
    }

    /**
     * 保存备注
     *
     * @param condition
     * @return
     */
    @PostMapping(value = "/updateOrderRemarks")
    @ApiOperation("更新订单信息备注")
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(value = "apply_order_info", allEntries = true)
    public IResponse updateOrderRemarks(@RequestBody ApplyReportCondition condition) {

        ApplyOrderInfo orderInfo = orderInfoService.getOrderInfoByApplyNo(condition.getApplyNo());
        if (orderInfo != null) {
            orderInfo.setRemarks(condition.getRemarks());
            orderInfoService.updateById(orderInfo);
        } else {
            return IResponse.fail("订单信息不存在");
        }
        return IResponse.success(Boolean.TRUE);
    }

    /**
     * 更新资产变更
     * @param condition
     * @return
     */
    @PostMapping(value = "/updateBodyContent")
    @ApiOperation("更新资产变更")
    @Transactional(rollbackFor = Exception.class)
    public IResponse updateBodyContent(@RequestBody AssetChangeCondition condition){

        if(CollectionUtil.isNotEmpty(condition.getCostList())){
            IResponse iResponse = modifyHistoryService.checkProductInfoForAsset(condition);
            if (!"0000".equals(iResponse.getCode())) {
                return iResponse;
            }
        }
        ApplyModifyHistory applyModifyHistory = modifyHistoryService.updateBodyContent(condition.getApplyNo(),condition.getCostList(),condition.getCarInfo());
        return IResponse.success(applyModifyHistory.getId().toString());
    }

}
